package com.lc.testScript;

/**
 * Created by 000001159 on 2016/8/12.
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.Test;


public class test {

    // 创建CookieStore实例
    static CookieStore cookieStore = null;
    static HttpClientContext context = null;
    String urls="http://172.18.100.62:8080";
//    String urls="http://localhost:8888";
    CloseableHttpClient client;
    String loginUrl = urls+"/sys/login";
    String testUrl = urls+"/customquery/getFirmUserInfo";
    String testUrl2=urls+"/json/getRoleInfo";
    String loginErrorUrl = "/sys/loginOut";

    @Test
    public void testLogin() throws Exception {
        System.out.println("----testLogin");

        client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(loginUrl);
        Map parameterMap = new HashMap();
        parameterMap.put("userName", "admin");
        parameterMap.put("userPwd", "1");
        UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8");
        httpPost.setEntity(postEntity);
        System.out.println("request line:" + httpPost.getRequestLine());
        try {
            // 执行post请求
            HttpResponse httpResponse = client.execute(httpPost);
            String location = httpResponse.getFirstHeader("Location").getValue();
            if (location != null && location.startsWith(loginErrorUrl)) {
                System.out.println("----loginError");
            }
//            printResponse(httpResponse);

            // 执行get请求
            System.out.println("----the same client");
            // cookie store
            setCookieStore(httpResponse);
            // context
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
//        HttpPost httpPost1 = new HttpPost(testUrl2);
//        //将cookieStore中的Cookie,放入Header中
////        httpPost.setHeader("Cookie", "JSESSIONID=" + cookieStore.getCookies().get(0).getValue().trim());
//        System.out.println("Cookie" + cookieStore.getCookies().get(0).getValue());
//        Map parameterMap1 = new HashMap();
//        parameterMap.put("page", "1");
//        parameterMap.put("rows", "10");
//        UrlEncodedFormEntity postEntity1 = new UrlEncodedFormEntity(getParam(parameterMap1), "UTF-8");
//
//        httpPost1.setEntity(postEntity1);
//        System.out.println("request line:" + httpPost1.getRequestLine());
//
//        try {
//            // 执行post请求
//            HttpResponse httpResponse = client.execute(httpPost1);
//            System.out.println("cookie store:" + cookieStore.getCookies());
//            printResponse(httpResponse);
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//
//        }
    }





    @Test
    public void testCookieStore2() throws Exception {
        System.out.println("----testCookieStore");
        // 使用cookieStore方式
        Thread.sleep(1000);
        client = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

        HttpPost httpPost = new HttpPost(testUrl2);
        //将cookieStore中的Cookie,放入Header中
        httpPost.setHeader("Cookie", "JSESSIONID=" + cookieStore.getCookies().get(0).getValue().trim());
        System.out.println("Cookie" + cookieStore.getCookies().get(0).getValue());
        Map parameterMap = new HashMap();
        parameterMap.put("page", "1");
        parameterMap.put("rows", "10");
        UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(getParam(parameterMap), "UTF-8");

        httpPost.setEntity(postEntity);
        System.out.println("request line:" + httpPost.getRequestLine());

        try {
            // 执行post请求
            HttpResponse httpResponse = client.execute(httpPost);
            System.out.println("cookie store:" + cookieStore.getCookies());
            printResponse(httpResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @After
    public void closeClient(){
        try {
            // 关闭流并释放资源
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void printResponse(HttpResponse httpResponse)
            throws ParseException, IOException {
        // 获取响应消息实体
        HttpEntity entity = httpResponse.getEntity();
        // 响应状态
        System.out.println("status:" + httpResponse.getStatusLine());
        System.out.println("headers:");
        HeaderIterator iterator = httpResponse.headerIterator();
        while (iterator.hasNext()) {
            System.out.println("\t" + iterator.next());
        }
        // 判断响应实体是否为空
        if (entity != null) {
            String responseString = EntityUtils.toString(entity);
            System.out.println("response length:" + responseString.length());
            System.out.println("response content:" + responseString.replace("\r\n", ""));
        }
    }



    public static void setCookieStore(HttpResponse httpResponse) {
        System.out.println("----setCookieStore");
        cookieStore = new BasicCookieStore();
        // JSESSIONID
        String setCookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
        String JSESSIONID = setCookie.substring("JSESSIONID=".length(), setCookie.indexOf(";"));
        System.out.println("JSESSIONID:" + JSESSIONID);
        // 新建一个Cookie
        BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", JSESSIONID);
        cookie.setVersion(0);
        cookie.setDomain("127.0.0.1");
        cookieStore.addCookie(cookie);
    }

    public static List<NameValuePair> getParam(Map parameterMap) {
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        Iterator it = parameterMap.entrySet().iterator();
        while (it.hasNext()) {
            Entry parmEntry = (Entry) it.next();
            param.add(new BasicNameValuePair((String) parmEntry.getKey(),
                    (String) parmEntry.getValue()));
        }
        return param;
    }
}
